<?php

class Core_Model_DbTable_CartProducts extends YouNet_Db_Table
{
    const TABLE_NAME = 'cart_products';
	protected $_name = self::TABLE_NAME;
	
	static private $_instance;
	public static function getInstance()
	{
		if (!(self::$_instance instanceof Core_Model_DbTable_CartProducts))
		{
			self::$_instance = new Core_Model_DbTable_CartProducts();
		}
		return self::$_instance;
	}
    
    public function addCartProducts($list_products, $id_cart){
        if(!empty($list_products)){
            foreach ($list_products as $product){
                if($product['quantity'] > 0){
                    $cart_product = array(
                        'id_cart'   => $id_cart,
                        'id_product'=> $product['id'],
                        'price'     => $product['price'],
                        'quantity'  => $product['quantity']
                    );
                    $this->insert($cart_product);
                }
            }
        }
    }
    
    public function getAllProductsInCart($id_cart)
    {
        $sql = $this->select()->setIntegrityCheck(false)
                ->from(array('cProducts' => self::TABLE_NAME), array('id_cart', 'cart_price' => 'cProducts.price', 'quantity'))
                ->join(array('product' => Core_Model_DbTable_Products::TABLE_NAME), 'cProducts.id_product = product.id')
                ->joinLeft(array('img' => Core_Model_DbTable_Product_Images::TABLE_NAME), 'img.id_product = product.id', array('image'))
                ->group('product.id')
                ->where('cProducts.id_cart = ?', $id_cart);
        return $this->fetchAll($sql);
    }
    
    public function getOrderHistoryDetail($id_cart)
    {
        $sql = $this->select()->setIntegrityCheck(false)
                ->from(array('cProducts' => self::TABLE_NAME), array('id_cart', 'cart_price' => 'cProducts.price', 'quantity'))
                ->join(array('product' => Core_Model_DbTable_Products::TABLE_NAME), 'cProducts.id_product = product.id')
                ->joinLeft(array('img' => Core_Model_DbTable_Product_Images::TABLE_NAME), 'img.id_product = product.id', array('image'))
                ->group('product.id')
                ->where('cProducts.id_cart = ?', $id_cart);
        return $this->fetchAll($sql);
    }
}